package com.qf.blog.email.listener;

import com.alibaba.fastjson.JSON;
import com.qf.blog.core.dto.EmailDto;
import com.qf.blog.core.utils.EmailUtils;
import com.qf.blog.email.entity.EmailErrorEntity;
import com.qf.blog.email.mapper.EmailErrorMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class EmailQueueListener {

    @Autowired
    private EmailErrorMapper emailErrorMapper;

    @RabbitListener(queues = "email-queue")
    public void consuemrMsg(EmailDto emailDto, Channel channel, Message message) {
        log.debug("邮箱服务开始发送邮件:{}", emailDto);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 邮件发送
            sendMsg(emailDto);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("邮件发送失败了:", e);

            // 把发送失败的邮件记录到MySQL中，给MQServler继续应答ACK===》持久化
            int insert = saveDB(emailDto);
            if (insert > 0) {
                try {
                    log.debug("邮件入库成功");
                    channel.basicAck(deliveryTag, false);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            } else {
                try {
                    log.debug("邮件入库失败");
                    channel.basicNack(deliveryTag, false, true);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    private Integer saveDB(EmailDto emailDto) {
        EmailErrorEntity entity = new EmailErrorEntity();
        entity.setCreateTime(new Date());
        entity.setStatus(1);
        entity.setEmailText(JSON.toJSONString(emailDto));
        return emailErrorMapper.insert(entity);
    }

    private void sendMsg(EmailDto emailDto) {
//        int status = EmailUtils.sendEmailInfoUser(emailDto);
        int x = 10 / 0;
    }
}
